const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const winston = require('../utils/logger');
const Admin = require('../models/Admin');

// 用户登录
const login = async (req, res) => {
    try {
        const { username, password } = req.body;
        winston.info('收到登录请求:', { body: req.body, headers: req.headers });

        // 查询用户
        const admin = await Admin.findOne({ where: { username } });
        winston.info('查询管理员结果:', { 
            found: !!admin, 
            username,
            adminData: admin ? {
                id: admin.id,
                username: admin.username,
                hasPassword: !!admin.password,
                passwordLength: admin.password?.length
            } : null
        });

        if (!admin) {
            return res.status(401).json({ message: '用户名或密码错误' });
        }

        const isValidPassword = await bcrypt.compare(password, admin.password);
        winston.info('密码验证结果:', { 
            hashedPassword: admin.password,
            inputPassword: password,
            isValid: isValidPassword
        });

        if (!isValidPassword) {
            winston.warn('密码错误:', { username });
            return res.status(401).json({ message: '用户名或密码错误' });
        }

        // 生成JWT token
        const token = jwt.sign(
            { id: admin.id, username: admin.username },
            process.env.JWT_SECRET,
            { expiresIn: process.env.JWT_EXPIRES_IN || '24h' }
        );

        res.json({ 
            token,
            admin: {
                id: admin.id,
                username: admin.username,
                name: admin.name
            }
        });
    } catch (error) {
        winston.error('登录错误:', error);
        res.status(500).json({ message: '服务器错误' });
    }
};

// 修改密码
const changePassword = async (req, res) => {
    try {
        const { currentPassword, newPassword, confirmPassword } = req.body;
        const adminId = req.user.id; // 从JWT中获取

        // 验证新密码
        if (newPassword !== confirmPassword) {
            return res.status(400).json({ message: '两次输入的新密码不一致' });
        }

        // 查询用户
        const admin = await Admin.findByPk(adminId);

        if (!admin) {
            return res.status(404).json({ message: '用户不存在' });
        }

        // 验证当前密码
        const isValidPassword = await bcrypt.compare(currentPassword, admin.password);
        if (!isValidPassword) {
            return res.status(401).json({ message: '当前密码错误' });
        }

        // 加密新密码
        const hashedPassword = await bcrypt.hash(newPassword, 10);

        // 更新密码
        await admin.update({ password: hashedPassword });

        res.json({ message: '密码修改成功' });
    } catch (error) {
        winston.error('修改密码错误:', error);
        res.status(500).json({ message: '服务器错误' });
    }
};

module.exports = {
    login,
    changePassword
}; 